import datetime
from haystack import indexes

from .models import Post


# 全文搜索配置步骤
# pipenv install django-haystack whoosh
# vi settings.py # add 'haystack' to INSTALL_APPS
# vi myapp/search_indexes.py
# vi templates/search/indexes/myapp/mymodel_text.txt
# python manage.py rebuid_index
# vi base.html # form # action="/search/" input#name="q"
# vi myproject/urls.py
# vi templates/search/search.html
class PostIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    # 给title, content, pub_date设置索引
    title = indexes.CharField(model_attr='title')
    content = indexes.CharField(model_attr='content')
    date_creatd = indexes.DateTimeField(model_attr='date_created')

    def get_model(self):
        return Post

    def index_queryset(self, using=None):
        """索引结果，文章发表时间不能大于当前时间，按发表时间降序排序"""
        return self.get_model().objects.filter(date_created__lte=datetime.datetime.now()).order_by('-date_created')
